package cn.com.jd.service.impl;


import java.sql.Date;
import java.util.Calendar;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.com.jd.common.CommonConstant;
import cn.com.jd.dao.CardDtoMapper;
import cn.com.jd.dao.GameaccountDtoMapper;
import cn.com.jd.dao.UserInfoDtoMapper;
import cn.com.jd.dto.RechargeDto;
import cn.com.jd.dto.StatusDto;
import cn.com.jd.model.CardDto;
import cn.com.jd.model.GameaccountDto;
import cn.com.jd.model.UserInfoDto;
import cn.com.jd.service.RechargeService;

@Service("RechargeService")
public class RechargeServiceImpl implements RechargeService {

	@Resource
	private UserInfoDtoMapper userInfoDtoMapper;
	@Resource
	private GameaccountDtoMapper gameaccountDtoMapper;
	@Resource
	private CardDtoMapper cardDtoMapper;
	
	@Override
	public StatusDto recharge(RechargeDto rc){
		StatusDto sts = new StatusDto();
		CardDto cd = cardDtoMapper.selectByPrimaryKey(rc.getCardNo());
		if(cd == null){
			sts.setSts(CommonConstant.ERROR);
			sts.setMsg(CommonConstant.INVALID_CARD);
			return sts;
		} else {
			CardDto crd = new CardDto();
			crd.setUsedFlag(CommonConstant.CARD_USED);
			crd.setCardId(rc.getCardNo());
			cardDtoMapper.updateByPrimaryKeySelective(crd);
			UserInfoDto ui = userInfoDtoMapper.selectByPrimaryKey(rc.getUserId());
			int maxAccelerateCountBefor = ui.getMaxAccount();
			Date expireDate = ui.getExpireDate();
			int addMonths = cd.getaccelerateMonths();
			Calendar cal1 = Calendar.getInstance();
			cal1.setTime(expireDate);
			cal1.add(Calendar.MONTH, addMonths);
			expireDate = new Date(cal1.getTime().getTime());
			ui.setExpireDate(expireDate);
			ui.setMaxAccount(cd.getMaxAccount());
			userInfoDtoMapper.updateByPrimaryKeySelective(ui);
			if(maxAccelerateCountBefor > cd.getMaxAccount()){
				gameaccountDtoMapper.clearExprieDate(rc.getUserId());
				sts.setSts(CommonConstant.WARNING);
				sts.setMsg(CommonConstant.RESELECT_ACCOUNT);
			} else {
				GameaccountDto ga = new GameaccountDto();
				ga.setExpireDate(expireDate);
				ga.setUserId(rc.getUserId());
				gameaccountDtoMapper.updateExprieDate(ga);
			}
			if(ui.getInvitedCd() != null){
				UserInfoDto uid = userInfoDtoMapper.selectByInviteCd(ui.getInvitedCd());
				cal1.setTime(uid.getExpireDate());
				cal1.add(Calendar.DAY_OF_MONTH, CommonConstant.GIFT_DAYS);
				UserInfoDto userInfoDto = new UserInfoDto();
				userInfoDto.setExpireDate(new Date(cal1.getTime().getTime()));
				userInfoDto.setUserId(uid.getUserId());
				userInfoDtoMapper.updateByPrimaryKeySelective(userInfoDto);
				GameaccountDto gameaccountDto = new GameaccountDto();
				gameaccountDto.setExpireDate(new Date(cal1.getTime().getTime()));
				gameaccountDto.setUserId(uid.getUserId());
				gameaccountDtoMapper.updateExprieDate(gameaccountDto);
			}
			sts.setExpireDate(expireDate);
			return sts;
		}
	}
}
